import { Controller, UseGuards, Delete, Body, Post, Get, Query, UseInterceptors, UploadedFile, Req, BadGatewayException } from '@nestjs/common';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { Subcode } from '@libs/db/models/subcode.models';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { SetSubcode } from './dto/setsubcode.dto';
import { GetSubcode, ListIp } from './dto/getsubcode.dto';
import { FileInterceptor } from "@nestjs/platform-express";
import { mkdirSync, accessSync, renameSync, unlinkSync, readdirSync, unlink } from "fs";
import { Qrcode } from '@libs/db/models/qrcode.models';
import { GetqrCodeOne } from './dto/getqrcodeone.dto';
import { InjectModel } from 'nestjs-typegoose';
import { IP } from '@libs/db/models/ip.models';


@Controller('subcode')
@ApiTags('子码模块')
@ApiBearerAuth()
@UseGuards(AuthGuard("jwt"))
export class SubcodeController {

    public imagepath: string = "public/uploads/"

    constructor(
        @InjectModel(Subcode) public SubcodeModel: ModelType<Subcode>,
        @InjectModel(Qrcode) public qrcodeModel: ModelType<Qrcode>,
        @InjectModel(IP) private IPModel: ModelType<IP>
    ) { }


    @ApiOperation({ summary: "上传子码" })
    @Post("upsubcode")
    @UseInterceptors(FileInterceptor('file'))
    async upsubcode(@UploadedFile() file, @Body() body, @Req() req): Promise<object> {
        if (body.suburl == 'error') {
            unlink(file.path, err => { })
            throw new BadGatewayException('无法解析')
        }
        const qrcode = await this.qrcodeModel.findById(body.qrcodeid)
        const path = this.imagepath + qrcode.shortid
        try {
            await accessSync(__dirname + "/" + path)
            renameSync(file.path, __dirname + "/" + path + "/" + file.filename)
        } catch (error) {
            mkdirSync(__dirname + "/" + path)
            renameSync(file.path, __dirname + "/" + path + "/" + file.filename)
        }

        file.path = path + "/" + file.filename
        const time = Math.floor(Date.now() / 1000);
        const data = {
            impression: 0,
            identifynum: 0,
            status: true,
            time
        }
        const upsubcode = await this.SubcodeModel.create({ ...file, ...body, ...data, userid: req.user._id })
        return upsubcode
    }



    @ApiOperation({ summary: "删除单条子码" })
    @Delete("delsubcode")
    async delqrcode(@Body() body, @Req() req): Promise<object> {
        const select = await this.SubcodeModel.find({ _id: { $in: body.id }, userid: req.user._id })
        const deletes = await this.SubcodeModel.deleteMany({ _id: { $in: body.id }, userid: req.user._id })
        this.IPModel.deleteMany({ subcodeid: body.id }).then()
        setTimeout(() => {
            try {
                select.forEach(async (item) => {
                    await unlinkSync(__dirname + "/" + item.path)
                })

            } catch (error) { }
        }, 100);
        return deletes
    }


    @ApiOperation({ summary: "删除全部子码" })
    @Delete("allsubcode")
    async delsubcodeall(@Body() body, @Req() req): Promise<object> {
        const select = await this.qrcodeModel.findOne({ _id: body.qrcodeid, userid: req.user._id })
        const deletes = await this.SubcodeModel.deleteMany({ qrcodeid: body.qrcodeid, userid: req.user._id })
        this.IPModel.deleteMany({ qrcode: body.qrcodeid }).then()
        setTimeout(() => {
            try {
                const path = __dirname + "/" + this.imagepath + select.shortid
                const files = readdirSync(path)
                for (var i = 0; i < files.length; i++) {
                    unlinkSync(path + "/" + files[i])
                }
            } catch (error) { }
        }, 100);
        return deletes;
    }


    @ApiOperation({ summary: "修改子码" })
    @Post("setsubcode")
    async setsubcode(@Body() body: SetSubcode, @Req() req): Promise<object> {
        const setqrcode = await this.SubcodeModel.updateOne({ _id: body.id, userid: req.user._id }, body)
        return setqrcode
    }



    @ApiOperation({ summary: "查询全部子码" })
    @Post("getsubcode")
    async getcodeall(@Body() body: GetSubcode, @Req() req): Promise<object> {
        const count = await this.SubcodeModel.countDocuments({ qrcodeid: body.id, userid: req.user._id })
        const getcodeall = await this.SubcodeModel.find({ qrcodeid: body.id, userid: req.user._id }).skip((body.page - 1) * 10).limit(10).sort({ '_id': -1 });
        return { total: count, date: getcodeall }
    }



    @ApiOperation({ summary: "查询单条子码" })
    @Get("getsubcode")
    async getsubcode(@Query() query: GetqrCodeOne, @Req() req): Promise<object> {
        const count = await this.SubcodeModel.countDocuments({ originalname: { $regex: query.name }, userid: req.user._id })
        const getqrcode = await this.SubcodeModel.find({ originalname: { $regex: query.name }, userid: req.user._id })
        return { total: count, date: getqrcode }
    }


    @ApiOperation({ summary: "查询子码ip列表" })
    @Post("listip")
    async listip(@Body() body: ListIp): Promise<object> {
        const count = await this.IPModel.countDocuments({ subcodeid: body.id })
        const listip = await this.IPModel.find({ subcodeid: body.id }).skip((body.page - 1) * 15).limit(15).sort({ 'time': -1 });
        return { total: count, data: listip }
    }


 
}
